package com.tcm.im.util;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.base.core.exception.ServiceException;
import com.tcm.im.config.HxConfig;
import com.tcm.im.dto.HxUserDTO;
import com.tcm.im.dto.Token;
import com.tcm.im.enums.HxMessageType;
import com.tcm.im.po.AudioMessage;
import com.tcm.im.po.ImageMessage;
import com.tcm.im.po.VideoMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;

@Component
public class HxUtil {

    @Autowired
    HxConfig hxConfig;

    @Autowired
    RestTemplate restTemplate;


    /**
     * 获取Token
     * token存在时间为7天，可以将token存入redis
     * @return token
     */
    public Token getToken() throws Exception {
        JSONObject body = new JSONObject();
        body.put("grant_type", "client_credentials");
        body.put("client_id", hxConfig.getClientId() );
        body.put("client_secret", hxConfig.getClientSecret() );
        HttpEntity httpEntity = new HttpEntity(body.toString(), null);
        String url = hxConfig.getUrlPrefix() + "token";
        org.springframework.http.ResponseEntity<Token> tokenResponseEntity = restTemplate.postForEntity(url, httpEntity, Token.class);
        Token token =  tokenResponseEntity.getBody();
        HttpStatus statusCode = tokenResponseEntity.getStatusCode();
        if(statusCode.value()==200){
            return token;
        }
        return null;
    }

    /**
     * 添加用户
     *
     * @param username 用户名（唯一非空）
     * @return 是否成功
     */
    public  Boolean addUser(String username) throws Exception {
        try {
            JSONArray body = new JSONArray();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("username", username);
            jsonObject.put("password", hxConfig.getPassword());
            body.add(jsonObject);
            HttpHeaders headers = new HttpHeaders();
            headers.add("Authorization", "Bearer " + getToken().getAccess_token());
            HttpEntity httpEntity = new HttpEntity(body.toString(), headers);
            org.springframework.http.ResponseEntity responseEntity = restTemplate.postForEntity(
                    hxConfig.getUrlPrefix() + "users", httpEntity, null);
            System.out.println(responseEntity.getStatusCodeValue());
            return responseEntity.getStatusCodeValue() == 200;
        } catch (RestClientException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 查询用户
     *
     * @param username 用户名（唯一非空）
     * @return 是否成功
     */
    public  String queryUser(String username) throws Exception {
        try {
            HttpEntity httpEntity = new HttpEntity(null, getHttpHeaders(MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON));
            org.springframework.http.ResponseEntity responseEntity = restTemplate.exchange(
                    hxConfig.getUrlPrefix() + "users/{username}",HttpMethod.GET, httpEntity, HxUserDTO.class, username);
            System.out.println(responseEntity.getStatusCodeValue());
            if(responseEntity.getStatusCodeValue() == 200){
                return responseEntity.getBody().toString();
            }
        } catch (RestClientException e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }

    /**
     * 修改用户密码
     *
     * @param username    用户名
     * @return 是否成功
     */
    public boolean updatePassword(String username) throws Exception {
        try {
            JSONObject body = new JSONObject();
            body.put("newpassword", hxConfig.getPassword());
            HttpHeaders headers = new HttpHeaders();
            headers.add("Authorization", "Bearer " + getToken().getAccess_token());
            HttpEntity httpEntity = new HttpEntity(body.toString(), headers);
            org.springframework.http.ResponseEntity responseEntity = restTemplate.postForEntity(
                    hxConfig.getUrlPrefix() + "users/{username}/password", httpEntity, null, username);
            System.out.println(responseEntity.getStatusCodeValue());
            return responseEntity.getStatusCodeValue() == 200;
        } catch (RestClientException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除用户
     *
     * @param username 用户名
     */
    public boolean deleteUser(String username) throws Exception{
        try {
            HttpEntity httpEntity = new HttpEntity(null, getHttpHeaders(MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON));
            org.springframework.http.ResponseEntity<HxUserDTO> responseEntity = restTemplate.exchange(
                    hxConfig.getUrlPrefix() + "users/{username}", HttpMethod.DELETE, httpEntity,
                    HxUserDTO.class, username);
            return responseEntity.getStatusCodeValue() == 200;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 添加好友
     *
     * @param ownerUsername 用户名
     * @param friendName    好友用户名
     * @return 是否成功
     */
    public boolean addFriend(String ownerUsername, String friendName) throws Exception {
        try {
            HttpEntity httpEntity = new HttpEntity(null, getHttpHeaders(MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON));
            org.springframework.http.ResponseEntity responseEntity = restTemplate.postForEntity(
                    hxConfig.getUrlPrefix() + "users/{owner_username}/contacts/users/{friend_username}",
                    httpEntity, HxUserDTO.class, ownerUsername, friendName);
            return responseEntity.getStatusCodeValue() == 200;
        } catch (RestClientException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除好友
     *
     * @param ownerUsername 用户名
     * @param friendName    好友用户名
     * @return 是否成功
     */
    public boolean deleteFriend(String ownerUsername, String friendName) throws Exception{
        try {
            HttpEntity httpEntity = new HttpEntity(null, getHttpHeaders(MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON));
            org.springframework.http.ResponseEntity responseEntity = restTemplate.exchange(
                    hxConfig.getUrlPrefix() + "users/{owner_username}/contacts/users/{friend_username}",
                    HttpMethod.DELETE, httpEntity, HxUserDTO.class, ownerUsername, friendName);
            System.out.println(responseEntity.getStatusCodeValue());
            return responseEntity.getStatusCodeValue() == 200;
        } catch (RestClientException e) {
            e.printStackTrace();
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 发送消息
     *
     * @param sendUser   发送用户
     * @param targetUser 接收用户
     * @param msg  发送消息
     * @return 是否成功
     */
    public  String sendMessage(String sendUser, String targetUser, String msg) throws Exception{
        try {
            JSONObject body = new JSONObject();
            body.put("target_type", "users");
            JSONArray targetUserjson = new JSONArray();
            targetUserjson.add(targetUser);
            body.put("target", targetUserjson);
            JSONObject msgJson = new JSONObject();
            msgJson.put("type", HxMessageType.TXT.name().toLowerCase());
            msgJson.put("msg", msg);
            body.put("msg", msgJson);
            body.put("from", sendUser);
            HttpEntity httpEntity = new HttpEntity(body.toString(), getHttpHeaders(MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON));
            org.springframework.http.ResponseEntity responseEntity = restTemplate.postForEntity(
                    hxConfig.getUrlPrefix() + "messages", httpEntity, null);
            Boolean rs = responseEntity.getStatusCodeValue() == 200;
            if(rs){
                return responseEntity.getBody().toString();
            }
            return null;
        } catch (RestClientException e) {
            e.printStackTrace();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 发送系统消息
     *
     * @param targetUser 接收用户
     * @param msg  发送消息
     * @return 是否成功
     */
    public  String sendMessage(String targetUser, String msg) throws Exception{
        try {
            JSONObject body = new JSONObject();
            body.put("target_type", "users");
            JSONArray targetUserjson = new JSONArray();
            targetUserjson.add(targetUser);
            body.put("target", targetUserjson);
            JSONObject msgJson = new JSONObject();
            msgJson.put("type", HxMessageType.TXT.name().toLowerCase());
            msgJson.put("msg", msg);
            body.put("msg", msgJson);
            HttpEntity httpEntity = new HttpEntity(body.toString(), getHttpHeaders(MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON));
            org.springframework.http.ResponseEntity responseEntity = restTemplate.postForEntity(
                    hxConfig.getUrlPrefix() + "messages", httpEntity, null);

            Boolean rs = responseEntity.getStatusCodeValue() == 200;
            if(rs){
                return responseEntity.getBody().toString();
            }
            return null;
        } catch (RestClientException e) {
            e.printStackTrace();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 发送图片消息
     *
     * @param sendUser   发送用户
     * @param targetUser 接收用户
     * @return 是否成功
     */
    public  String sendImageMessage(String sendUser, String targetUser, ImageMessage imageMessage) throws Exception{
        try {
            JSONObject body = new JSONObject();
            body.put("target_type", "users");
            JSONArray targetUserjson = new JSONArray();
            targetUserjson.add(targetUser);
            body.put("target", targetUserjson);
            JSONObject msgJson = new JSONObject();
            msgJson.put("type", HxMessageType.IMG.name().toLowerCase());
            msgJson.put("msg", imageMessage.getMessage());
            msgJson.put("filename",imageMessage.getFilename());
            msgJson.put("url",imageMessage.getUrl());
            msgJson.put("secret", imageMessage.getSecret());
            JSONObject sizeJson = new JSONObject();
            sizeJson.put("height", imageMessage.getHeight());
            sizeJson.put("width",imageMessage.getWidth());
            msgJson.put("size",sizeJson);
            body.put("msg", msgJson);
            body.put("from", sendUser);
            String s = body.toString();
            HttpEntity httpEntity = new HttpEntity(body, getHttpHeaders(MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON));

            org.springframework.http.ResponseEntity responseEntity = restTemplate.postForEntity(
                    hxConfig.getUrlPrefix() + "messages", httpEntity, null);
            Boolean rs = responseEntity.getStatusCodeValue() == 200;
            if(rs){
                return responseEntity.getBody().toString();
            }
            return null;
        } catch (RestClientException e) {
            e.printStackTrace();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 发送语音消息
     *
     * @param sendUser   发送用户
     * @param targetUser 接收用户
     * @return 是否成功
     */
    public  String sendAudioMessage(String sendUser, String targetUser, AudioMessage audioMessage) throws Exception{
        try {
            JSONObject body = new JSONObject();
            body.put("target_type", "users");
            JSONArray targetUserjson = new JSONArray();
            targetUserjson.add(targetUser);
            body.put("target", targetUserjson);
            JSONObject msgJson = new JSONObject();
            msgJson.put("type", HxMessageType.AUDIO.name().toLowerCase());
            msgJson.put("filename",audioMessage.getFilename());
            msgJson.put("url",audioMessage.getUrl());
            msgJson.put("secret", audioMessage.getSecret());
            msgJson.put("length",audioMessage.getLength());
            body.put("msg", msgJson);
            body.put("from", sendUser);
            HttpEntity httpEntity = new HttpEntity(body.toString(), getHttpHeaders(MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON));
            org.springframework.http.ResponseEntity responseEntity = restTemplate.postForEntity(
                    hxConfig.getUrlPrefix() + "messages", httpEntity, null);
            Boolean rs = responseEntity.getStatusCodeValue() == 200;
            if(rs){
                return responseEntity.getBody().toString();
            }
            return null;
        } catch (RestClientException e) {
            e.printStackTrace();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 发送图片消息
     *
     * @param sendUser   发送用户
     * @param targetUser 接收用户
     * @return 是否成功
     */
    public  String sendVideoMessage(String sendUser, String targetUser, VideoMessage videoMessage) throws Exception{
        try {
            JSONObject body = new JSONObject();
            body.put("target_type", "users");
            JSONArray targetUserjson = new JSONArray();
            targetUserjson.add(targetUser);
            body.put("target", targetUserjson);
            JSONObject msgJson = new JSONObject();
            msgJson.put("type", HxMessageType.VIDEO.name().toLowerCase());
            msgJson.put("filename",videoMessage.getFilename());
            msgJson.put("url",videoMessage.getUrl());
            msgJson.put("secret", videoMessage.getSecret());
            msgJson.put("thumb", videoMessage.getThumb());
            msgJson.put("length", videoMessage.getLength());
            msgJson.put("thumb_secret", videoMessage.getThumbSecret());
            msgJson.put("file_length", videoMessage.getFileLength());
            body.put("msg", msgJson);
            body.put("from", sendUser);
            HttpEntity httpEntity = new HttpEntity(body.toString(), getHttpHeaders(MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON));
            org.springframework.http.ResponseEntity responseEntity = restTemplate.postForEntity(
                    hxConfig.getUrlPrefix() + "messages", httpEntity, null);
            Boolean rs = responseEntity.getStatusCodeValue() == 200;
            if(rs){
                return responseEntity.getBody().toString();
            }
            return null;
        } catch (RestClientException e) {
            e.printStackTrace();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取HttpHeaders
     *
     * @param contentType 客户端发送类型
     * @param accept      响应类型
     * @return HttpHeaders
     */
    private HttpHeaders getHttpHeaders(MediaType contentType, MediaType... accept) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        //设置
        headers.add("Authorization", "Bearer " + getToken().getAccess_token());
        headers.setContentType(contentType != null ? contentType : MediaType.APPLICATION_JSON);
        headers.setAccept(Arrays.asList((accept != null && accept.length > 0) ? accept : new MediaType[]{MediaType.APPLICATION_JSON}));
        return headers;
    }
}
